<?php

namespace app\api\controller\Card;

use think\Controller;
use think\Request;

class Card extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->TypeModel = model('Card.Type');
        $this->CardModel = model('Card.Card');
        $this->OrderModel = model('Card.Order');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('Record');
    }
    // 分类接口
    public function type()
    {
        $typelist = $this->TypeModel->select();

        $this->success('查询成功', null, $typelist);
    }
    //当前登录用户的生成名片
    public function card()
    {
        $userid  = $this->request->param('userid');
        $card = $this->CardModel->with(['type'])->where(['userid' => $userid])->find();
        $this->success('查询成功', null, $card);
    }
    //添加生成名片
    public function add()
    {
        $params = $this->request->param();
        $card = $this->CardModel->where(['id' => $params['cardid'], 'userid' => $params['userid']])->find();
        if ($card) {
            // 更新
            $data = [
                'id' => $params['cardid'],
                'userid' => $params['userid'],
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'sex' => $params['sex'],
                'content' => $params['content'],
                'typeid' => $params['typeid'],
                'price' => 20
            ];

            if (!empty($params['code'])) {
                $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');
                if (!$parentpath) {
                    $this->error('所选地区不存在');
                }
                // [$province, $city, $district] = explode(',', $parentpath);
                $array = explode(',', $parentpath);
                $province = $array[0];
                $city = $array[1];
                $district = $array[2];

                if ($province) {
                    $data['province'] = $province;
                }
                if ($city) {
                    $data['city'] = $city;
                }
                if ($district) {
                    $data['district'] = $district;
                }
            }

            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = upload('avatar');
                if ($avatar['code'] === 1) {
                    $data['avatar'] = $avatar['data'];
                }
            }

            $result = $this->CardModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
                }
                $this->error($this->CardModel->getError());
            } else {
                $user = model('User.User')->find($params['userid']);

                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0 && $card['avatar'] != $user['avatar']) {
                    @is_file('.' . $card['avatar']) && unlink('.' . $card['avatar']);
                }
                $this->success('生成成功');
            }
        } else {
            // 新增
            $data = [
                'userid' => $params['userid'],
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'sex' => $params['sex'],
                'content' => $params['content'],
                'typeid' => $params['typeid'],
                'price' => 20
            ];

            if (!empty($params['code'])) {
                $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');
                if (!$parentpath) {
                    $this->error('所选地区不存在');
                }
                // [$province, $city, $district] = explode(',', $parentpath);
                $array = explode(',', $parentpath);
                $province = $array[0];
                $city = $array[1];
                $district = $array[2];

                if ($province) {
                    $data['province'] = $province;
                }
                if ($city) {
                    $data['city'] = $city;
                }
                if ($district) {
                    $data['district'] = $district;
                }
            }

            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = upload('avatar');
                if ($avatar['code'] === 1) {
                    $data['avatar'] = $avatar['data'];
                }
            } else {
                $user = model('User.User')->find($params['userid']);
                if ($user) {
                    $data['avatar'] = $user['avatar'];
                }
            }
            // halt($data);
            $result = $this->CardModel->validate('common/Card/Card')->save($data);
            if ($result === FALSE) {
                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
                }
                $this->error($this->CardModel->getError());
            } else {
                $this->success('生成成功');
            }
        }
    }
    //列表查询
    public function list()
    {
        $userid = $this->request->param('userid');
        $typeid = $this->request->param('typeid', 0);
        $keyword = $this->request->param('keyword');
        /* 
            查询card的数据不包含自身的数据 查询条件 userid <> $userid
        */
        $where = [];
        $CardidArr = $this->OrderModel->where(['userid' => $userid])->column('cardid');
        if ($userid) {
            $where['userid'] = ['<>', $userid];
        }
        if ($CardidArr) {
            $where['id'] = ['NOT IN', $CardidArr];
        }
        if ($typeid) {
            $where['typeid'] = $typeid;
        }
        if ($keyword) {
            $where['nickname'] = ['like', "%$keyword%"];
        }

        $CardList = $this->CardModel->where($where)->select();
        // echo $this->CardModel->getLastsql();
        // exit();
        $this->success('查询成功', null, $CardList);
    }
    //购买
    public function pay()
    {
        $userid = $this->request->param('userid');
        $cardid = $this->request->param('cardid');
        $price = $this->request->param('price');
        $Card = $this->CardModel->find($cardid);
        $User = $this->UserModel->find($userid);

        if (!$Card) {
            $this->error('该名片不存在，请重新选择');
        }
        if (!$User) {
            $this->error('非法登录,请重新登录');
        }

        // 开启事务
        $this->OrderModel->startTrans();
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();

        // 订单数据
        $OrderData = [
            'userid' => $userid,
            'cardid' => $cardid,
            'price' => $price
        ];
        $OrderStatus = $this->OrderModel->validate('common/Card/Order')->save($OrderData);
        if ($OrderStatus === FALSE) {
            $this->error($this->OrderModel->getError());
        }

        // 用户
        $UserData = [
            'id' => $userid,
            'point' => bcsub($User['point'], $price)
        ];
        $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
        if ($UserStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->error($this->UserModel->getError());
        }

        // 新增消费记录
        $RecordData = [
            'point' => $price,
            'content' => "您的购买名片共消费了{$price}积分",
            'state' => 7,
            'userid' => $userid
        ];
        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
        if ($RecordStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        if ($RecordStatus === FALSE || $OrderStatus === FALSE || $UserStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error('购买失败');
        } else {
            $this->OrderModel->commit();
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $this->success('购买成功');
        }
    }
}
